package cn.wildfire.chat.app.extendsion.ui;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import cn.wildfire.chat.app.extendsion.classes.UserCard;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.extendsion.widgets.CircleImageView;
import cn.wildfirechat.message.Message;
import cn.wildfirechat.message.TextMessageContent;
import cn.wildfirechat.message.UserCardMessageContent;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;
import cn.wildfirechat.remote.SendMessageCallback;

/**
 * Create by HEKE, 2019/9/23 21:09
 * TODO 发送个人名片窗口
 */
public class SendUserCardWindow implements View.OnClickListener {

    TextView tvSendTo;
    CircleImageView cvSendToUserHead;
    TextView sendTouserName;
    EditText sendMessage;
    TextView tvUserName;
    TextView btnCancel;
    TextView btnConfirm;

    private Context mContext;
    private UserInfo friendUserInfo;
    private UserInfo targetUserInfo;
    private UserInfo selfUserInfo;

    private PopupWindow window;
    private View mView;

    private boolean showing;

    private OnSenduserCardWindowListener onSenduserCardWindowListener;

    private void initViews() {
        try {
            tvSendTo = mView.findViewById(R.id.tv_send_to);
            cvSendToUserHead = mView.findViewById(R.id.cv_send_to_user_head);
            sendMessage = mView.findViewById(R.id.sendMessage);
            sendTouserName = mView.findViewById(R.id.sendToUserName);
            tvUserName = mView.findViewById(R.id.tv_user_name);
            btnCancel = mView.findViewById(R.id.btn_cancel);
            btnConfirm = mView.findViewById(R.id.btn_confirm);
            btnCancel.setOnClickListener(this);
            btnConfirm.setOnClickListener(this);

            window = new PopupWindow(mContext);
            window.setContentView(mView);
            window.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
            window.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
            window.setFocusable(true);
            window.setTouchable(true);
            window.setOutsideTouchable(true);
            window.setBackgroundDrawable(new ColorDrawable(0x30000000));
            window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    showing = false;
                }
            });
            // 加载好友备注名称、设置接收方
            String friendName = friendUserInfo.friendAlias;
            if (TextUtils.isTextEmpty(friendName)) {
                friendName = friendUserInfo.groupAlias;
                if (TextUtils.isTextEmpty(friendName)) {
                    friendName = friendUserInfo.displayName;
                }
            }
            tvUserName.setText("" + friendName);
            friendName = targetUserInfo.friendAlias;
            if (TextUtils.isTextEmpty(friendName)) {
                friendName = targetUserInfo.groupAlias;
                if (TextUtils.isTextEmpty(friendName)) {
                    friendName = targetUserInfo.displayName;
                }
            }
            sendTouserName.setText("" + friendName);
            // 加载头像等信息
            Glide.with(mContext).load(targetUserInfo.portrait).apply(new RequestOptions().
                    placeholder(R.mipmap.avatar_def).centerCrop()).into(cvSendToUserHead);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SendUserCardWindow(Context context, UserInfo friendUserInfo, UserInfo targetUserInfo, UserInfo selfUserInfo
            , OnSenduserCardWindowListener onSenduserCardWindowListener) {
        this.mContext = context;
        this.friendUserInfo = friendUserInfo;
        this.targetUserInfo = targetUserInfo;
        this.selfUserInfo = selfUserInfo;
        this.onSenduserCardWindowListener = onSenduserCardWindowListener;
        this.mView = View.inflate(this.mContext.getApplicationContext(), R.layout.pop_recommend_to_friend, null);
        initViews();
    }

    public boolean isShowing() {
        return showing;
    }

    public void show(View anchorView) {
        if (isShowing()) {
            return;
        }
        if (anchorView == null) {
            window.showAtLocation(mView, Gravity.CENTER, 0, 0);
            showing = true;
        }
    }

    public void hide() {
        if (!isShowing()) {
            return;
        }
        showing = false;
        window.dismiss();
    }

    /**
     * 发送信息
     */
    private void send() {
        try {
            TipDialog tipDialog = new TipDialog(mContext);
            tipDialog.setTitle("");
            tipDialog.setContent(mContext.getString(R.string.share_in_msg));
            tipDialog.show();
            // 留言
            String sendMsg = sendMessage.getText().toString();
            // 新建推送消息
            Message message = new Message();
            message.sender = selfUserInfo.uid;
            message.toUsers = new String[]{selfUserInfo.uid, targetUserInfo.uid};
            // 新建会话内容
            Conversation conversation = new Conversation(Conversation.ConversationType.Single, targetUserInfo.uid);
            message.conversation = conversation;
            // 新建用户名片信息
            String friendName = TextUtils.isTextEmpty(friendUserInfo.friendAlias) ? friendUserInfo.displayName : friendUserInfo.friendAlias;
            UserCard userCard = new UserCard(friendUserInfo.uid, friendName, friendUserInfo.portrait);
            UserCardMessageContent userCardMessageContent = new UserCardMessageContent();
            userCardMessageContent.content = userCard.toJson();
            message.content = userCardMessageContent;
            // 发送个人名片消息
            ChatManager.Instance().sendMessage(message, new SendMessageCallback() {
                @Override
                public void onSuccess(long messageUid, long timestamp) {
                    if (TextUtils.isTextEmpty(sendMsg)) {
                        // 发送完毕
                        tipDialog.dismiss();
                        ToastTip.tip(mContext.getString(R.string.share_usercard_success));
                        ((Activity) mContext).finish();
                    } else {
                        sendLiveMessage(tipDialog, message, sendMsg);
                    }
                }

                @Override
                public void onFail(int errorCode) {
                    ToastTip.tip(mContext.getString(R.string.share_usercard_failure));
                }

                @Override
                public void onPrepare(long messageId, long savedTime) {
                }

            });
        } catch (Exception e) {
            e.printStackTrace();
            ToastTip.tip(mContext.getString(R.string.share_usercard_failure));
        }
    }

    /**
     * 发送留言信息
     */
    private void sendLiveMessage(TipDialog tipDialog, Message message, String sendMsg) {
        try {
            // 发送留言信息
            TextMessageContent textMessageContent = new TextMessageContent();
            textMessageContent.setContent(sendMsg);
            message.content = textMessageContent;
            ChatManager.Instance().sendMessage(message, new SendMessageCallback() {
                @Override
                public void onSuccess(long messageUid, long timestamp) {
                    // 发送完毕
                    tipDialog.dismiss();
                    ToastTip.tip(mContext.getString(R.string.share_usercard_success));
                    ((Activity) mContext).finish();
                }

                @Override
                public void onFail(int errorCode) {
                    ToastTip.tip(mContext.getString(R.string.share_usercard__msg_failure));
                }

                @Override
                public void onPrepare(long messageId, long savedTime) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_cancel) {
            if (onSenduserCardWindowListener != null) {
                onSenduserCardWindowListener.cancle();
            }
            hide();
        } else if (id == R.id.btn_confirm) {
            send();
            hide();
        }
    }

    public interface OnSenduserCardWindowListener {
        void cancle();
    }

}
